package com.simplehire.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.simplehire.model.User;
import com.simplehire.service.DeepSeekService;
import com.simplehire.service.FileProcessingService;
import com.simplehire.service.MockDeepSeekService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.security.Principal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简历分析控制器 - MVP V1
 * 核心功能：简历解析 + 基础输出
 */
@Controller
@RequestMapping("/resume")
public class ResumeAnalysisController {

    private static final Logger logger = LoggerFactory.getLogger(ResumeAnalysisController.class);
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private FileProcessingService fileProcessingService;
    
    @Autowired
    private DeepSeekService deepSeekService;
    
    @Autowired(required = false)
    private MockDeepSeekService mockDeepSeekService;

    /**
     * 显示简历分析页面
     */
    @GetMapping("/analysis")
    public String showAnalysisPage(Model model) {
        // 初始化模板变量，避免Thymeleaf解析错误
        model.addAttribute("success", false);
        model.addAttribute("error", null);
        model.addAttribute("message", null);
        return "resume-analysis";
    }
    
    /**
     * 测试页面
     */


    /**
     * 处理简历文件上传和分析
     */
    @PostMapping("/upload")
    public String uploadAndAnalyze(@RequestParam("resumeFile") MultipartFile file,
                                  Authentication authentication,
                                  Model model,
                                  RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "请选择要上传的简历文件。");
                return "redirect:/resume/analysis";
            }
            
            if (!fileProcessingService.isValidFileType(file.getOriginalFilename())) {
                redirectAttributes.addFlashAttribute("error", 
                    "不支持的文件格式。支持的格式：" + fileProcessingService.getSupportedFileTypes());
                return "redirect:/resume/analysis";
            }
            
            if (!fileProcessingService.isValidFileSize(file.getSize())) {
                redirectAttributes.addFlashAttribute("error", 
                    "文件大小不能超过" + fileProcessingService.getMaxFileSizeMB() + "MB。");
                return "redirect:/resume/analysis";
            }
            
            // 提取简历文本
            String resumeText = fileProcessingService.extractTextFromFile(file);
            
            // 分析简历内容
            String analysisResult = analyzeResume(resumeText);
            
            // 解析分析结果为结构化数据
            Map<String, Object> structuredData = parseAnalysisResult(analysisResult);
            
            // 添加到模型
            model.addAttribute("fileName", file.getOriginalFilename());
            model.addAttribute("fileSize", formatFileSize(file.getSize()));
            model.addAttribute("resumeText", resumeText);
            model.addAttribute("analysisResult", analysisResult);
            model.addAttribute("structuredData", structuredData);
            model.addAttribute("success", true);
            
            return "resume-analysis";
            
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/resume/analysis";
        } catch (UnsupportedOperationException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/resume/analysis";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "处理简历文件时出错：" + e.getMessage());
            return "redirect:/resume/analysis";
        }
    }

    /**
     * 处理简历文本分析
     */
    @PostMapping("/analyze-text")
    public String analyzeText(@RequestParam("resumeText") String resumeText,
                             Authentication authentication,
                             Model model,
                             RedirectAttributes redirectAttributes) {
        
        try {
            if (resumeText == null || resumeText.trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "请输入简历文本内容。");
                return "redirect:/resume/analysis";
            }
            
            if (resumeText.length() > 10000) {
                redirectAttributes.addFlashAttribute("error", "简历文本长度不能超过10000字符。");
                return "redirect:/resume/analysis";
            }
            
            // 分析简历内容
            String analysisResult = analyzeResume(resumeText);
            
            // 解析分析结果为结构化数据
            Map<String, Object> structuredData = parseAnalysisResult(analysisResult);
            
            // 添加到模型
            model.addAttribute("resumeText", resumeText);
            model.addAttribute("analysisResult", analysisResult);
            model.addAttribute("structuredData", structuredData);
            model.addAttribute("success", true);
            model.addAttribute("isTextInput", true);
            
            return "resume-analysis";
            
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "分析简历文本时出错：" + e.getMessage());
            return "redirect:/resume/analysis";
        }
    }

    /**
     * 分析简历内容
     */
    private String analyzeResume(String resumeText) {
        try {
            // 调用AI服务进行结构化信息提取
            String analysisResult = deepSeekService.extractResumeStructuredInfo(resumeText);
            logger.info("AI分析结果: {}", analysisResult);
            return analysisResult;
        } catch (Exception e) {
            // 如果DeepSeek服务失败，使用模拟服务
            System.out.println("DeepSeek服务不可用，使用模拟服务: " + e.getMessage());
            if (mockDeepSeekService != null) {
                return mockDeepSeekService.analyzeResume(resumeText);
            } else {
                return generateDefaultAnalysis();
            }
        }
    }

    /**
     * 生成默认分析结果
     */
    private String generateDefaultAnalysis() {
        return "【基本信息】：\n" +
               "- 姓名：[从简历中提取]\n" +
               "- 联系方式：[从简历中提取]\n" +
               "- 教育背景：[从简历中提取]\n\n" +
               "【技能总结】：\n" +
               "- 编程语言：[从简历中提取]\n" +
               "- 框架技术：[从简历中提取]\n" +
               "- 数据库：[从简历中提取]\n" +
               "- 其他技能：[从简历中提取]\n\n" +
               "【工作经历】：\n" +
               "- [从简历中提取工作经历]\n\n" +
               "【项目经验】：\n" +
               "- [从简历中提取项目经验]\n\n" +
               "【简历评估】：\n" +
               "- 优势：[分析简历优势]\n" +
               "- 不足：[分析简历不足]\n" +
               "- 改进建议：[提供改进建议]";
    }

    /**
     * 解析分析结果为结构化数据
     */
    private Map<String, Object> parseAnalysisResult(String analysisResult) {
        Map<String, Object> data = new HashMap<>();
        
        try {
            // 清理AI返回的结果，移除markdown代码块标记
            String cleanedResult = cleanJsonFromMarkdown(analysisResult);
            
            // 首先尝试解析JSON格式的结果
            if (cleanedResult.trim().startsWith("{")) {
                data = parseJsonAnalysisResult(cleanedResult);
            } else {
                // 解析文本格式的结果
                data = parseTextAnalysisResult(analysisResult);
            }
            
        } catch (Exception e) {
            logger.error("解析分析结果时出错: {}", e.getMessage());
            // 返回默认结构
            data = createDefaultStructuredData();
        }
        
        return data;
    }
    
    /**
     * 从markdown格式中提取纯JSON
     */
    private String cleanJsonFromMarkdown(String text) {
        if (text == null) {
            return "{}";
        }
        
        // 移除markdown代码块标记
        String cleaned = text.trim();
        if (cleaned.startsWith("```json")) {
            cleaned = cleaned.substring(7); // 移除 ```json
        }
        if (cleaned.startsWith("```")) {
            cleaned = cleaned.substring(3); // 移除 ```
        }
        if (cleaned.endsWith("```")) {
            cleaned = cleaned.substring(0, cleaned.length() - 3); // 移除结尾的 ```
        }
        
        return cleaned.trim();
    }

    /**
     * 解析JSON格式的分析结果
     */
    private Map<String, Object> parseJsonAnalysisResult(String jsonResult) {
        Map<String, Object> data = new HashMap<>();
        
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResult);
            
            // 解析基本信息
            if (rootNode.has("basicInfo")) {
                data.put("basicInfo", objectMapper.convertValue(rootNode.get("basicInfo"), Map.class));
            }
            
            // 解析教育背景
            if (rootNode.has("education")) {
                data.put("education", objectMapper.convertValue(rootNode.get("education"), List.class));
            }
            
            // 解析技能总结
            if (rootNode.has("skills")) {
                data.put("skills", objectMapper.convertValue(rootNode.get("skills"), Map.class));
            }
            
            // 解析项目经验
            if (rootNode.has("projects")) {
                data.put("projects", objectMapper.convertValue(rootNode.get("projects"), List.class));
            }
            
            // 解析评分信息
            if (rootNode.has("scoring")) {
                data.put("scoring", objectMapper.convertValue(rootNode.get("scoring"), Map.class));
            }
            
            // 解析分析结果
            if (rootNode.has("analysis")) {
                data.put("analysis", objectMapper.convertValue(rootNode.get("analysis"), Map.class));
            }
            
            // 解析风险评估
            if (rootNode.has("riskAssessment")) {
                data.put("riskAssessment", objectMapper.convertValue(rootNode.get("riskAssessment"), Map.class));
            }
            
            // 解析工作经历
            if (rootNode.has("workExperience")) {
                data.put("workExperience", rootNode.get("workExperience").asText());
            }
            
            // 解析项目经验
            if (rootNode.has("projectExperience")) {
                data.put("projectExperience", rootNode.get("projectExperience").asText());
            }
            
            // 解析简历评估
            if (rootNode.has("evaluation")) {
                data.put("evaluation", objectMapper.convertValue(rootNode.get("evaluation"), Map.class));
            }
            
            // 解析评分信息
            if (rootNode.has("scoring")) {
                data.put("scoring", objectMapper.convertValue(rootNode.get("scoring"), Map.class));
            }
            
            // 解析分析结果
            if (rootNode.has("analysis")) {
                data.put("analysis", objectMapper.convertValue(rootNode.get("analysis"), Map.class));
            }
            
            // 解析风险评估
            if (rootNode.has("riskAssessment")) {
                data.put("riskAssessment", objectMapper.convertValue(rootNode.get("riskAssessment"), Map.class));
            }
            
            // 解析面试重点
            if (rootNode.has("interviewFocus")) {
                data.put("interviewFocus", objectMapper.convertValue(rootNode.get("interviewFocus"), List.class));
            }
            
            // 解析市场价值
            if (rootNode.has("marketValue")) {
                data.put("marketValue", rootNode.get("marketValue").asText());
            }
            
        } catch (Exception e) {
            logger.error("解析JSON分析结果时出错: {}", e.getMessage());
            // 返回默认的结构化数据而不是抛出异常
            return createDefaultStructuredData();
        }
        
        return data;
    }

    /**
     * 解析文本格式的分析结果
     */
    private Map<String, Object> parseTextAnalysisResult(String analysisResult) {
        Map<String, Object> data = new HashMap<>();
        
        // 解析基本信息
        Map<String, String> basicInfo = extractSection(analysisResult, "【基本信息】");
        data.put("basicInfo", basicInfo);
        
        // 解析技能总结
        Map<String, String> skills = extractSection(analysisResult, "【技能总结】");
        data.put("skills", skills);
        
        // 解析工作经历
        String workExperience = extractSectionContent(analysisResult, "【工作经历】");
        data.put("workExperience", workExperience);
        
        // 解析项目经验
        String projectExperience = extractSectionContent(analysisResult, "【项目经验】");
        data.put("projectExperience", projectExperience);
        
        // 解析简历评估
        Map<String, String> evaluation = extractSection(analysisResult, "【简历评估】");
        data.put("evaluation", evaluation);
        
        return data;
    }

    /**
     * 创建默认的结构化数据
     */
    private Map<String, Object> createDefaultStructuredData() {
        Map<String, Object> data = new HashMap<>();
        
        // 基本信息
        Map<String, String> basicInfo = new HashMap<>();
        basicInfo.put("name", "未知");
        basicInfo.put("email", "未提供");
        basicInfo.put("phone", "未提供");
        basicInfo.put("location", "未提供");
        basicInfo.put("currentPosition", "未提供");
        data.put("basicInfo", basicInfo);
        
        // 技能信息
        Map<String, Object> skills = new HashMap<>();
        skills.put("programmingLanguages", new ArrayList<>());
        skills.put("frameworks", new ArrayList<>());
        skills.put("databases", new ArrayList<>());
        skills.put("tools", new ArrayList<>());
        skills.put("softSkills", new ArrayList<>());
        data.put("skills", skills);
        
        // 项目经验
        data.put("projects", new ArrayList<>());
        
        // 评分信息
        Map<String, Integer> scoring = new HashMap<>();
        scoring.put("overallScore", 60);
        scoring.put("technicalSkills", 60);
        scoring.put("experience", 60);
        scoring.put("education", 60);
        scoring.put("projectComplexity", 60);
        data.put("scoring", scoring);
        
        // 分析结果
        Map<String, Object> analysis = new HashMap<>();
        analysis.put("strengths", new ArrayList<>());
        analysis.put("recommendations", new ArrayList<>());
        analysis.put("careerAdvice", "暂无分析");
        analysis.put("marketValue", "暂无评估");
        data.put("analysis", analysis);
        
        // 风险评估
        Map<String, String> riskAssessment = new HashMap<>();
        riskAssessment.put("jobStability", "中等");
        riskAssessment.put("careerProgression", "中等");
        riskAssessment.put("skillRelevance", "中等");
        data.put("riskAssessment", riskAssessment);
        
        // 面试重点
        data.put("interviewFocus", new ArrayList<>());
        
        // 其他字段
        data.put("workExperience", "");
        data.put("projectExperience", "");
        data.put("evaluation", new HashMap<String, String>());
        data.put("marketValue", "暂无评估");
        
        return data;
    }

    /**
     * 提取章节内容为键值对
     */
    private Map<String, String> extractSection(String text, String sectionTitle) {
        Map<String, String> section = new HashMap<>();
        
        int startIndex = text.indexOf(sectionTitle);
        if (startIndex == -1) return section;
        
        int endIndex = text.indexOf("【", startIndex + sectionTitle.length());
        if (endIndex == -1) endIndex = text.length();
        
        String sectionContent = text.substring(startIndex + sectionTitle.length(), endIndex);
        String[] lines = sectionContent.split("\n");
        
        for (String line : lines) {
            line = line.trim();
            if (line.startsWith("-") && line.contains("：")) {
                String[] parts = line.substring(1).split("：", 2);
                if (parts.length == 2) {
                    section.put(parts[0].trim(), parts[1].trim());
                }
            }
        }
        
        return section;
    }

    /**
     * 提取章节内容为字符串
     */
    private String extractSectionContent(String text, String sectionTitle) {
        int startIndex = text.indexOf(sectionTitle);
        if (startIndex == -1) return "";
        
        int endIndex = text.indexOf("【", startIndex + sectionTitle.length());
        if (endIndex == -1) endIndex = text.length();
        
        return text.substring(startIndex + sectionTitle.length(), endIndex).trim();
    }

    /**
     * 格式化文件大小
     */
    private String formatFileSize(long size) {
        if (size < 1024) {
            return size + " B";
        } else if (size < 1024 * 1024) {
            return String.format("%.1f KB", size / 1024.0);
        } else {
            return String.format("%.1f MB", size / (1024.0 * 1024.0));
        }
    }
}